<?php

namespace app\admin\controller;

use app\admin\model\CorplibCzy;
use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 客户
 *
 */
class Corplib extends Backend
{
    /**
     * Corplib模型对象
     * @var \app\admin\model\Corplib
     */
    protected $model = null;
    protected $type=null;
    protected $corpsq=null;
    protected $quickSearchField = ['CORP'];
    protected $defaultSortField = 'OPTIME,desc';
    protected $noNeedLogin      = ['*'];

    protected $preExcludeFields = [''];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\Corplib;
        $this->corpsq =new \app\admin\model\XCorpsq();
    }
    /**
     * 查看
     * corp 公司名称
     * type  公司类别
     * sy_type 首页代码
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $type=$this->request->get('type');
        $crop=$this->request->get('CORP');
        $sy_type=$this->request->get('code');
        $wheres=[];
        if($crop){
            $wheres['CORP']=$crop;
        }
        if($type==1){
            $wheres['COMPANYTYPE']='客户';
        }elseif($type==2){
            $wheres['COMPANYTYPE']='供应商';
        }
        $sy_where=[];
        if($sy_type){
            if($sy_type=='DLXKZ'){
                $sy_where="exists ( select * from X_CERTIFICATE where corp=corplib.corp and zjname='道路运营证' and datediff(day,getdate(),YXQDATE)<(select isnull(max(CAST(attr as int)),0) from codelib where code='DLXKZ' and codetype='alarmsetup') )";
            }elseif($sy_type=='JSZ'){
                $sy_where="exists (select * from x_driver where CORP=corplib.CORP AND  datediff(day,getdate(),jszdate)<(select isnull(max(CAST(attr as int)),0) from codelib where code='JSZ' and codetype='alarmsetup')) ";
            }elseif($sy_type=='CLBX'){
                $sy_where=" exists (select * from x_carinfo where corp=corplib.corp and datediff(day,getdate(),policydate)<(select isnull(max(CAST(attr as int)),0) from codelib where code='CLBX' and codetype='alarmsetup')) ";
            }elseif($sy_type=='CLNJ'){
                $sy_where="where exists (select * from x_carinfo where corp=corplib.corp and datediff(day,getdate(),jydate)<(select isnull(max(CAST(attr as int)),0) from codelib where code='CLNJ' and codetype='alarmsetup')) "    ;
            }elseif($sy_type=='AQZG'){
                $sy_where="exists (select * from x_security where corp=corplib.corp and isnull(finished,'')<>'1') and corplib.companytype='供应商'  "    ;
            }elseif($sy_type=='GYSHT'){
                $sy_where="corplib.COMPANYTYPE='供应商'  and exists ( select * from x_certificate where corp=corplib.corp and datediff(day,getdate(),yxqdate)<(select isnull(max(CAST(attr as int)),0) from codelib where code='GYSZJ' and codetype='alarmsetup'))"    ;
            }elseif($sy_type=='GYSZJ'){
                $sy_where="COMPANYTYPE='供应商' and exists ( select * from x_certificate where corp=corplib.corp and datediff(day,getdate(),yxqdate)<(select isnull(max(CAST(attr as int)),0) from codelib where code='GYSZJ' and codetype='alarmsetup')) "    ;
            }
        }
        $adminInfo          = $this->auth->getInfo();
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field('corplib.*,DEPARTMENT.DEPTNAME')
            ->join('DEPARTMENT',"corplib.DEPT=DEPARTMENT.DEPTID")
            ->with('czy')
            ->alias($alias)
            ->where($wheres)
            ->where($where)
            ->where($sy_where)
            ->order($order)
//            ->fetchSql()->select();
            ->paginate($limit);
//var_dump($res);die;

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);

            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $adminInfo          = $this->auth->getInfo();
            $data['OP']=$adminInfo['nickname'];
            $data['OPTIME']=date('Y-m-d H:i:s',time());
            if(!isset($data['DEPT']))$data['DEPT']=$adminInfo['department'];
            $result = false;
            //供应商需要判断审批按钮是否有效
            $status='';
            Db::startTrans();
            try {

                if(isset($data['GSTYPE'])){
                    $gstype=[];
                    //添加到公司分类
                    Db::table('customtype')->where('CORP',$data['CORP'])->delete();
                    foreach ($data['GSTYPE'] as $k=>$item) {
                        $gstype[$k]=['CORP'=>$data['CORP'],'CODE'=>$item];
                    }
                    Db::table('customtype')->insertAll($gstype);
                }
                if(isset($data['CZY'])){
                    $czy=[];

                    foreach ( $data['CZY']as $k=>$item) {
                        $czy[$k]=['CORP'=>$data['CORP'],'CZY'=>$item,'OP'=>$adminInfo['nickname'],'OPTIME'=>date('Y-m-d H:i:s',time())];
                    }
                    Db::table('corplibczy')->insertAll($czy);
                }

                if($data['type']==1){
                    $data['COMPANYTYPE']='客户';
                }else{
                    $data['COMPANYTYPE']='供应商';
                    $status=$this->getcorpsq($data['CORP']);
                    $data['ACTIVE']=0;
                    $data['LOCK']=0;
                }
                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {

                $this->success(__('Added successfully'),['status'=>$status]);
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }
    /**
     * 删除
     * @param array $ids
     */
    public function del(array $ids = [])
    {
        if (!$this->request->isDelete() || !$ids) {
            $this->error(__('Parameter error'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $this->model->where($this->dataLimitField, 'in', $dataLimitAdminIds);
        }

        $pk    = $this->model->getPk();
        $data  = $this->model->where($pk, 'in', $ids)->select();
        foreach ($data as $datum) {
            $sql='select  dbo.f_getcorpcount('.$datum['CORP'].') as status';
            $status=Db::query($sql);
            if($status==1){
                $this->error('数据包含有业务，不能删除');
            }
        }

        $count = 0;
        Db::startTrans();
        try {
            foreach ($data as $v) {
                $count += $v->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success(__('Deleted successfully'));
        } else {
            $this->error(__('No rows were deleted'));
        }
    }
    /**
     * 编辑
     */
    public function edit()
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }
        //判断审批状态改lock
        $sp=$this->corpsq->field('BIZNO,SQTYPE')->where('CORP',$id)->order('BIZNO','desc')->find();
        if($sp){
            $s=$this->status($sp['BIZNO']);
            $up=[];
            if($s=='已退回'){
                if($sp['SQTYPE']=='新增'){
                    $up=['LOCK'=>0];
                }
            }elseif ($s=='已完成'){
                if($sp['SQTYPE']=='新增'){
                    $up=['ACTIVE'=>1,'LOCK'=>1];
                }else{
                    $up=['LOCK'=>0];
                }
            }
            $row->save($up);
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
//                $code=explode(',',$data['COMPANYTYPE']);
                if(isset($data['GSTYPE'])) {
                    $type = [];
                    Db::table('customtype')->where('CORP',$data['CORP'])->delete();
                    //添加到公司分类
                    foreach ($data['GSTYPE'] as $k => $item) {
                        $type[$k] = ['CORP' => $data['CORP'], 'CODE' => $item];
                    }
                    Db::table('customtype')->insertAll($type);
                }
                if(isset($data['CZY'])) {
                    $czy = [];
                    $adminInfo          = $this->auth->getInfo();
                    Db::table('corplibczy')->where('CORP', $data['CORP'])->delete();
                    foreach ($data['CZY'] as $k => $item) {
                        $czy[$k] = ['CORP' => $data['CORP'], 'CZY' => $item, 'OP' => $adminInfo['nickname'], 'OPTIME' => date('Y-m-d', time())];
                    }
                    Db::table('corplibczy')->insertAll($czy);
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }
        $status='';
        //审批按钮
        if($row['COMPANYTYPE']=='供应商')     $status=$this->getcorpsq($row['CORP']);

        //获取类型
        $row['GSTYPE']=Db::table('customtype')->where('CORP',$row['CORP'])->column('CODE');
        $row['CZY']= Db::table('corplibczy')->where('CORP',$row['CORP'])->column('CZY');
        $row['status']=$status;
        $this->success('', [
            'row' => $row,
        ]);
    }
    /**
     * @throws \think\db\exception\DbException
     * 获取投诉对象
     */
    public function tsname(){
        $res=$this->model->field('corp')->where('COMPANYTYPE','供应商')->paginate();;
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 提交审批按钮
     */
    public function tj(){
       $post=$this->request->post();
        $corp=$this->model->where('CORP',$post['CORP'])->find();

        $adminInfo          = $this->auth->getInfo();
           $data['CORP']=$corp['CORP'];
           $data['CORPNAME']=$corp['CORPNAME'];
           $data['ENAME']=$corp['ENAME'];
           $data['DEPT']=$corp['DEPT'];
           $data['OP']=$adminInfo['nickname'];
           $data['OPTIME']=date('Y-m-d H:i:s',time());
           $data['BIZNO']='GY'. $this->microtime_format('YmdHisx',$this->microtime_float());
           $data['SQTYPE']=isset($post['type'])?'新增':'修改';
           $this->corpsq->save($data);
           $bizno= $data['BIZNO'];
       $s= $this->createflowdata($bizno,$corp['DEPT'],'供应商审批',0);
       if($s==200){
         $this->model->where('CORP',$post['CORP'])->save(['LOCK'=>1]);
         $this->success('提交成功');
       }else{
           $this->error('提交失败');
       }
    }

    /**
     * 获取公司类型
     */
    public function custtype(){
        $get=$this->request->get('type');
        $da=Db::table('customtype')->where('code',$get)->where("exists (select * from corplib where corplib.corp=customtype.corp and corplib.active='1')")->select();
        $this->success('',$da);
    }

}